<template>
  <div class="app-container home">
    <div class="dashboard-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>系统类型分布</span>
            </div>
            <div class="chart-container">
              <div ref="systemTypePie" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>操作系统分布</span>
            </div>
            <div class="chart-container">
              <div ref="osTypePie" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>中间件使用情况</span>
            </div>
            <div class="chart-container">
              <div ref="middlewareBar" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>系统级别分布</span>
            </div>
            <div class="chart-container">
              <div ref="systemLevelBar" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>数据库使用情况</span>
            </div>
            <div class="chart-container">
              <div ref="databaseBar" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>应用软件产品使用情况</span>
            </div>
            <div class="chart-container">
              <div ref="appProductBar" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getAssetStatistics } from "@/api/admin/asset";

export default {
  name: "Index",
  data() {
    return {
      // 图表实例
      charts: {
        systemTypePie: null,
        osTypePie: null,
        middlewareBar: null,
        systemLevelBar: null,
        databaseBar: null,
        appProductBar: null
      },
      // 统计数据
      statistics: {
        systemTypeStats: [],
        osTypeStats: [],
        middlewareStats: [],
        systemLevelStats: [],
        databaseStats: [],
        appProductStats: []
      },
      // 定时器
      refreshTimer: null,
      // 颜色列表
      colorList: [
        '#5470c6',
        '#91cc75',
        '#fac858',
        '#ee6666',
        '#73c0de',
        '#3ba272',
        '#fc8452',
        '#9a60b4'
      ],
      statsTimer: null, // 添加定时器变量
    };
  },
  created() {
    this.getStatistics();
    // 启动自动刷新
    this.startAutoRefresh();
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
    });
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
    this.getStatData(); // 首次加载时获取统计数据
    // 设置定时器，每60秒刷新一次数据
    this.statsTimer = setInterval(() => {
      this.getStatData();
    }, 60000);
  },
  beforeDestroy() {
    // 移除监听
    window.removeEventListener('resize', this.handleResize);
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });
    // 清除定时器
    this.stopAutoRefresh();
    // 组件销毁前清除定时器
    if (this.statsTimer) {
      clearInterval(this.statsTimer);
      this.statsTimer = null;
    }
  },
  methods: {
    /** 获取统计数据 */
    async getStatistics() {
      try {
        console.log('开始获取统计数据');
        const response = await getAssetStatistics();
        console.log('获取到的统计数据:', response);
        if (response.code === 200) {
          this.statistics = response.data;
          // 确保图表已经初始化
          this.$nextTick(() => {
            this.updateCharts();
          });
        } else {
          this.$modal.msgError(response.msg || '获取统计数据失败');
        }
      } catch (error) {
        console.error('获取统计数据失败:', error);
        this.$modal.msgError('获取统计数据失败');
      }
    },
    /** 启动自动刷新 */
    startAutoRefresh() {
      this.stopAutoRefresh();
      this.refreshTimer = setInterval(() => {
        this.getStatistics();
      }, 30000); // 30秒刷新一次
    },
    /** 停止自动刷新 */
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },
    /** 初始化图表 */
    initCharts() {
      console.log('初始化图表');
      if (this.$refs.systemTypePie) {
        this.charts.systemTypePie = echarts.init(this.$refs.systemTypePie);
      }
      if (this.$refs.osTypePie) {
        this.charts.osTypePie = echarts.init(this.$refs.osTypePie);
      }
      if (this.$refs.middlewareBar) {
        this.charts.middlewareBar = echarts.init(this.$refs.middlewareBar);
      }
      if (this.$refs.systemLevelBar) {
        this.charts.systemLevelBar = echarts.init(this.$refs.systemLevelBar);
      }
      if (this.$refs.databaseBar) {
        this.charts.databaseBar = echarts.init(this.$refs.databaseBar);
      }
      if (this.$refs.appProductBar) {
        this.charts.appProductBar = echarts.init(this.$refs.appProductBar);
      }
      
      // 如果已有数据，立即更新图表
      if (this.statistics.systemTypeStats && this.statistics.systemTypeStats.length > 0) {
        this.updateCharts();
      }
    },
    /** 更新图表数据 */
    updateCharts() {
      console.log('更新图表数据:', this.statistics);
      // 系统类型饼图
      if (this.charts.systemTypePie && this.statistics.systemTypeStats) {
        this.charts.systemTypePie.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center'
          },
          series: [{
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'outside'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            data: this.statistics.systemTypeStats
          }]
        }, true);
      }

      // 操作系统饼图
      if (this.charts.osTypePie && this.statistics.osTypeStats) {
        this.charts.osTypePie.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center'
          },
          series: [{
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'outside'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            data: this.statistics.osTypeStats
          }]
        }, true);
      }

      // 中间件柱状图
      if (this.charts.middlewareBar && this.statistics.middlewareStats) {
        this.charts.middlewareBar.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.statistics.middlewareStats.map(item => item.name),
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            type: 'bar',
            data: this.statistics.middlewareStats.map(item => item.value),
            itemStyle: {
              normal: {
                color: (params) => {
                  return this.colorList[params.dataIndex % this.colorList.length];
                }
              }
            },
            label: {
              show: true,
              position: 'top'
            }
          }]
        }, true);
      }

      // 系统级别柱状图
      if (this.charts.systemLevelBar && this.statistics.systemLevelStats) {
        this.charts.systemLevelBar.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.statistics.systemLevelStats.map(item => item.name),
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            type: 'bar',
            data: this.statistics.systemLevelStats.map(item => item.value),
            itemStyle: {
              normal: {
                color: (params) => {
                  return this.colorList[params.dataIndex % this.colorList.length];
                }
              }
            },
            label: {
              show: true,
              position: 'top'
            }
          }]
        }, true);
      }

      // 数据库柱状图
      if (this.charts.databaseBar && this.statistics.databaseStats) {
        this.charts.databaseBar.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.statistics.databaseStats.map(item => item.name),
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            type: 'bar',
            data: this.statistics.databaseStats.map(item => item.value),
            itemStyle: {
              normal: {
                color: (params) => {
                  return this.colorList[params.dataIndex % this.colorList.length];
                }
              }
            },
            label: {
              show: true,
              position: 'top'
            }
          }]
        }, true);
      }

      // 应用软件产品柱状图
      if (this.charts.appProductBar && this.statistics.appProductStats) {
        this.charts.appProductBar.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.statistics.appProductStats.map(item => item.name),
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            type: 'bar',
            data: this.statistics.appProductStats.map(item => item.value),
            itemStyle: {
              normal: {
                color: (params) => {
                  return this.colorList[params.dataIndex % this.colorList.length];
                }
              }
            },
            label: {
              show: true,
              position: 'top'
            }
          }]
        }, true);
      }
    },
    /** 处理窗口大小变化 */
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize();
        }
      });
    },
    getStatData() {
      // 获取统计数据的方法
      // ... existing code ...
    },
  }
};
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}

.dashboard-container {
  padding: 20px;
}
.chart-container {
  position: relative;
  width: 100%;
  padding: 20px 0;
}
</style>

